using EnterpriseApi.Data;
// <copyright file="Program.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Models;
using EnterpriseApi.Repositories;
using EnterpriseApi.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;

/// <summary>
/// 应用程序入口点类
/// 负责配置和启动ASP.NET Core应用程序
/// </summary>
public class Program
{
    /// <summary>
    /// 应用程序入口点方法
    /// 配置服务并构建应用程序管道
    /// </summary>
    /// <param name="args">命令行参数</param>
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // 添加控制器服务
        ConfigureServices(builder.Services, builder.Configuration);

        var app = builder.Build();

        // 配置HTTP请求管道
        ConfigurePipeline(app);

        app.Run();
    }

    /// <summary>
    /// 配置应用程序服务
    /// 注册控制器、数据库上下文、仓储、服务和Swagger等
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置对象</param>
    private static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        // 添加控制器服务
        services.AddControllers();

        // 配置Swagger/OpenAPI文档
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "EnterpriseApi", Version = "v1" });
            
        });

        // 配置数据库上下文
        services.AddDbContext<AppDbContext>(options =>
            options.UseMySql(
                configuration.GetConnectionString("DefaultConnection"),
                new MySqlServerVersion(new Version(8, 0, 36))));

        // 注册仓储服务
        services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<IProductRepository, ProductRepository>();
        services.AddScoped<ICategoryRepository, CategoryRepository>();
        services.AddScoped<IRoleRepository, RoleRepository>();

        // 注册业务服务
        services.AddScoped(typeof(IService<>), typeof(Service<>));
        services.AddScoped<IUserService, UserService>();
        services.AddScoped<IProductService, ProductService>();
        services.AddScoped<ICategoryService, CategoryService>();
        services.AddScoped<IRoleService, RoleService>();
    }

    /// <summary>
    /// 配置HTTP请求管道
    /// 设置中间件顺序和环境特定配置
    /// </summary>
    /// <param name="app">Web应用程序实例</param>
    private static void ConfigurePipeline(WebApplication app)
    {
        // 配置开发环境的中间件
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "EnterpriseApi v1"));
        }

        // 使用HTTPS重定向中间件
        app.UseHttpsRedirection();

        // 使用授权中间件
        app.UseAuthorization();

        // 映射控制器路由
        app.MapControllers();
    }
}
